package com.app.controller.exportExcel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.common.ApplyTool;
import com.app.common.SystemConstant;
import com.app.mapper.ApplyMapper;
import com.app.mapper.PersonMapper;
import com.app.mapper.TaskMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.vo.LevelVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.app.common.SystemConstant.ApplyExportURL;

/**
 * 试验任务：导出
 */
@RestController
@Controller
@RequestMapping("/api/excel")
public class TestTaskController {
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProtectionPointService protectionPointService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private PersonService personService;
    @Autowired
    private TestsService testsService;
    @Autowired
    private TestsPersonService testsPersonService;
    @Autowired
    private TestFailureService testFailureService;
    @Autowired
    private TestsRecordService testsRecordService;
    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private TaskMapper taskMapper;

    /**
     * 保护点信息导出 批量导出
     *
     * @param response
     * @throws IOException
     */
    @PostMapping("/protectionPointExcel")
    @ResponseBody
    public void protectionPoint(@RequestBody JSONObject json, HttpServletResponse response) {
        String ids = json.get("ids").toString();
        String[] items = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
        //获取列表
        List<ProtectionPointModel> list = protectionPointService.getPlantByIds(appIdList);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getDepartmentId() != null) {
                DepartmentModel depByDepId = departmentService.getDepByDepId(list.get(i).getDepartmentId());
                if (depByDepId != null) {
                    list.get(i).setDepartmentName(depByDepId.getName());
                }
            }
            list.get(i).setAddress(list.get(i).getLongitude() + "," + list.get(i).getLatitude());
        }
        map.put("list", list);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.ProtectionExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "保护点信息花名册" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 型号信息批量导出
     */
    @PostMapping("/modelTypeExcel")
    public void modelTypeExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        String ids = json.get("ids").toString();
        Map<String, Object> map = new HashMap<>();
        String[] items = ids.split(",");
        List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
        //获取列表
        List<TypeModel> typeModelList = typeService.getPlantByIds(appIdList);
        for (int i = 0; i < typeModelList.size(); i++) {
            if (typeModelList.get(i).getDepartmentId() != null) {
                DepartmentModel depByDepId = departmentService.getDepByDepId(typeModelList.get(i).getDepartmentId());
                if (depByDepId != null) {
                    typeModelList.get(i).setDepartmentText(depByDepId.getName());
                }
            }
        }
        map.put("list", typeModelList);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.TypeExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "型号信息花名册" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 试验信息批量导出
     */
    @PostMapping("/testExcel")
    public void testExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        String ids = json.get("id").toString();
        String[] items = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
        //获取列表
        List<TestsModel> testsModels = testsService.getPlantByIds(appIdList);
        for (int i = 0; i < testsModels.size(); i++) {
            if (testsModels.get(i).getDepartmentId() != null) {
                DepartmentModel depByDepId = departmentService.getDepByDepId(testsModels.get(i).getDepartmentId());
                if (depByDepId != null) {
                    testsModels.get(i).setDepartmentName(depByDepId.getName());
                }
            }
        }
        map.put("list", testsModels);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.TestExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "试验信息花名册" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 试验信息单个导出
     */
    @PostMapping("/exportTestsExcel")
    public void exportTestsExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        Integer id = (Integer) json.get("id");
        Map<String, Object> map = new HashMap<>();
        //获取列表
        TestsModel model = testsService.selectTestById(id);
        model.setTimeRange(model.getStartTime() + " -- " + model.getEndTime());//开始结束时间
        DepartmentModel departmentModel = departmentService.getDepByDepId(model.getDepartmentId());
        model.setDepartmentName(departmentModel.getName());//部门名称
        List<String> personName = new ArrayList<>();
        List<TestsPersonModel> personModelList = testsPersonService.getTestsPersonList(model.getId());
        for (int i = 0; i < personModelList.size(); i++) {
            PersonModel personModel1 = personService.selectPersonById(personModelList.get(i).getPersonId());
            personName.add(personModel1.getName());
        }
        model.setPersonName(StringUtils.join(personName, ","));
        map.put("model", model);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.TestOneExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "试验信息表" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 试验记录导出
     *
     * @param json
     * @param response
     */
    @PostMapping("/testsRecordExcel")
    public void testsRecordExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        String ids = json.get("ids").toString();
        String[] items = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
        //获取列表
        List<TestsRecordModel> testsRecordModels = testsRecordService.getPlantByIds(appIdList);
        for (int i = 0; i < testsRecordModels.size(); i++) {
            if (testsRecordModels.get(i).getDepartmentId() != null) {
                DepartmentModel depByDepId = departmentService.getDepByDepId(testsRecordModels.get(i).getDepartmentId());
                if (depByDepId != null) {
                    testsRecordModels.get(i).setDepartmentName(depByDepId.getName());
                }
            }
        }
        map.put("list", testsRecordModels);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.TestsRecordExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "试验记录花名册" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 试验故障导出
     *
     * @param json
     * @param response
     */
    @PostMapping("/testFailureExcel")
    public void testFailureExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        String ids = json.get("ids").toString();
        String[] items = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
        //获取列表
        List<TestFailureModel> TestFailureModels = testFailureService.getPlantByIds(appIdList);
        for (int i = 0; i < TestFailureModels.size(); i++) {
            if (TestFailureModels.get(i).getIsUse() == 1) {
                TestFailureModels.get(i).setIsUseText("是");
            } else {
                TestFailureModels.get(i).setIsUseText("否");
            }
        }
        map.put("list", TestFailureModels);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.TestFailureExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "试验故障花名册" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 大纲-报告-项目-研究
     *
     * @param json
     * @param response
     */
    @PostMapping("/taskExcel")
    public void taskExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        String ids = json.get("ids").toString();
        String[] items = ids.split(",");
        Map<String, Object> map = new HashMap<>();
        List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
        //获取列表
        QueryWrapper<TaskModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().in("id", appIdList);
        List<TaskModel> taskModels = taskMapper.selectList(queryWrapper);
        for (int i = 0; i < taskModels.size(); i++) {
            List<String> idsList = Arrays.asList(taskModels.get(i).getDepartmentId().split(","));
            taskModels.get(i).setDepartment(idsList);
            List<DepartmentModel> depByDepId = departmentService.getDepList(idsList);
            StringBuilder sb = new StringBuilder();
            for (DepartmentModel departmentModel : depByDepId) {
                sb.append(departmentModel.getName()).append(" | ");
            }
            sb.deleteCharAt(sb.length() - 2);
            taskModels.get(i).setDepartmentText(sb.toString());
        }
        map.put("list", taskModels);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.Task);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "大纲-报告-项目-研究" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/applyListExcel")
    @ResponseBody
    public void applyListExcel(@RequestBody JSONObject json, HttpServletResponse response) {
        String startTime = "";
        String endTime = "";
        if (json.containsKey("startTime") && json.get("startTime") != null) {
            startTime = json.get("startTime").toString();
        }
        if (json.containsKey("endTime") && json.get("endTime") != null) {
            endTime = json.get("endTime").toString();
        }
        Map<String, Object> map = new HashMap<>();
        if (StrUtil.isBlank(startTime) || StrUtil.isBlank(endTime)) {
            // 获取当前日期和时间
            LocalDateTime currentDateTime = LocalDateTime.now();
            // 获取当前日期的起始时间和结束时间
            startTime = Timestamp.valueOf(currentDateTime.toLocalDate().atStartOfDay()).toString();
            endTime = Timestamp.valueOf(currentDateTime.toLocalDate().atTime(LocalTime.MAX)).toString();
        }
        List<PersonModel> personModels = personMapper.selectList(null);
        HashMap<Integer, PersonModel> integerPersonModelHashMap = new HashMap<>();
        for (PersonModel personModel : personModels) {
            integerPersonModelHashMap.put(personModel.getId(), personModel);
        }
        List<LevelVo> levelVoList = ApplyTool.LEVEL_VO_LIST;
        HashMap<Integer, String> integerStringHashMap = new HashMap<>();
        for (LevelVo levelVo : levelVoList) {
            integerStringHashMap.put(levelVo.getId(), levelVo.getLevelName());
        }
        Wrapper<ApplyModel> wq = new QueryWrapper<ApplyModel>()
                .apply("NOT(end_time <' " + startTime + " 'OR start_time > '" + endTime + "')");
        List<ApplyModel> applyModels = applyMapper.selectList(wq);
        for (int i = 0; i < applyModels.size(); i++) {
            applyModels.get(i).setSeries(i + 1);
        }
        for (ApplyModel applyModel : applyModels) {
            if (applyModel.getCancellation() != null) {
                if (applyModel.getCancellation() == 1) {
                    applyModel.setCancellationText("未销假");
                } else {
                    applyModel.setCancellationText("已销假");
                }
            }

        }
        applyModels.forEach(applyModel -> {
            applyModel.setTypeText(integerStringHashMap.get(applyModel.getType()));
            applyModel.setName(integerPersonModelHashMap.get(applyModel.getPersonId()).getName());
        });
        map.put("list", applyModels);
        ClassPathResource classPathResource = new ClassPathResource(ApplyExportURL);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "外出人员列表" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}